/**
 * Copyright (c) iwindplus Technologies Co., Ltd.2024-2030, All rights reserved.
 */

package com.iwindplus.mgt.server.service.power.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.tree.Tree;
import cn.hutool.core.lang.tree.TreeNodeConfig;
import cn.hutool.core.lang.tree.TreeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.toolkit.SqlHelper;
import com.github.yulichang.repository.JoinCrudRepository;
import com.google.common.collect.Lists;
import com.iwindplus.boot.domain.enums.BizCodeEnum;
import com.iwindplus.boot.domain.enums.EnableStatusEnum;
import com.iwindplus.boot.domain.exception.BizException;
import com.iwindplus.boot.domain.vo.FilePathVO;
import com.iwindplus.boot.redis.manager.SerialNumManager;
import com.iwindplus.mgt.domain.dto.power.MenuEditDTO;
import com.iwindplus.mgt.domain.dto.power.MenuSaveDTO;
import com.iwindplus.mgt.domain.enums.MgtCodeEnum;
import com.iwindplus.mgt.domain.enums.MgtCodePrefixEnum;
import com.iwindplus.mgt.domain.vo.power.MenuBaseListSystemVO;
import com.iwindplus.mgt.domain.vo.power.MenuBaseTreeCheckedVO;
import com.iwindplus.mgt.domain.vo.power.MenuBaseTreeVO;
import com.iwindplus.mgt.domain.vo.power.MenuExtendVO;
import com.iwindplus.mgt.domain.vo.power.MenuListSystemVO;
import com.iwindplus.mgt.domain.vo.power.MenuTreeSystemVO;
import com.iwindplus.mgt.domain.vo.power.MenuTreeVO;
import com.iwindplus.mgt.domain.vo.power.MenuVO;
import com.iwindplus.mgt.server.config.property.MgtProperty;
import com.iwindplus.mgt.server.mapper.power.MenuMapper;
import com.iwindplus.mgt.server.model.power.MenuDO;
import com.iwindplus.mgt.server.model.power.ResourceDO;
import com.iwindplus.mgt.server.service.power.MenuService;
import com.iwindplus.mgt.server.service.power.ResourceService;
import com.iwindplus.mgt.server.service.power.RoleMenuService;
import com.iwindplus.mgt.server.service.power.RoleResourceService;
import com.iwindplus.setup.client.OssClient;
import jakarta.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.function.Function;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 资源业务层接口实现类.
 *
 * @author zengdegui
 * @since 2018/9/1
 */
@Slf4j
@Service
@CacheConfig(cacheNames = {"menu"})
@Transactional(rollbackFor = Exception.class)
public class MenuServiceImpl extends JoinCrudRepository<MenuMapper, MenuDO> implements MenuService {

    @Resource
    private RoleMenuService roleMenuService;

    @Resource
    private RoleResourceService roleResourceService;

    @Resource
    private ResourceService resourceService;

    @Resource
    private OssClient ossClient;

    @Resource
    private SerialNumManager serialNumManager;

    @Resource
    private MgtProperty property;

    @CacheEvict(allEntries = true)
    @Override
    public boolean save(MenuSaveDTO entity) {
        entity.setStatus(EnableStatusEnum.ENABLE);
        entity.setBuildInFlag(Boolean.FALSE);
        this.getNameIsExist(entity.getName().trim(), entity.getParentId(), entity.getSystemId());
        entity.setSeq(this.getNextSeq(entity.getParentId(), entity.getSystemId()));
        entity.setLevel(this.getLevel(entity.getParentId(), entity.getSystemId()));
        if (CharSequenceUtil.isBlank(entity.getCode())) {
            entity.setCode(this.serialNumManager.getSerialNum(MgtCodePrefixEnum.MENU_PREFIX.getValue()));
        } else {
            if (entity.getCode().startsWith(MgtCodePrefixEnum.MENU_PREFIX.getValue())) {
                throw new BizException(MgtCodeEnum.MENU_PREFIX_ERROR);
            }
        }
        this.getCodeIsExist(entity.getCode());
        if (CharSequenceUtil.isNotBlank(entity.getRouteUrl())) {
            this.getRouteUrlIsExist(entity.getRouteUrl().trim(), entity.getParentId(), entity.getSystemId());
        }
        final MenuDO model = BeanUtil.copyProperties(entity, MenuDO.class);
        super.save(model);
        entity.setId(model.getId());
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean removeByIds(List<Long> ids) {
        List<MenuDO> list = super.listByIds(ids);
        if (CollUtil.isEmpty(list)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        boolean match = list.stream().anyMatch(MenuDO::getBuildInFlag);
        if (Boolean.TRUE.equals(match)) {
            throw new BizException(BizCodeEnum.HAS_BUILD_IN_DATA);
        }
        // 判断是否有子集
        boolean data = SqlHelper.retBool(super.count(Wrappers.lambdaQuery(MenuDO.class)
            .in(MenuDO::getParentId, ids)));
        if (data) {
            throw new BizException(MgtCodeEnum.CHILDREN_NOT_DELETED);
        }
        // 判断是否有资源
        final boolean hasResource = SqlHelper.retBool(this.resourceService.count(Wrappers.lambdaQuery(ResourceDO.class)
            .in(ResourceDO::getMenuId, ids)));
        if (Boolean.TRUE.equals(hasResource)) {
            throw new BizException(MgtCodeEnum.RESOURCE_NOT_DELETED);
        }
        this.roleMenuService.removeByMenuIds(ids);
        this.roleResourceService.removeByMenuIds(ids);
        super.removeByIds(ids);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean edit(MenuEditDTO entity) {
        MenuDO data = super.getById(entity.getId());
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (CharSequenceUtil.isNotBlank(entity.getName()) && !CharSequenceUtil.equals(data.getName(), entity.getName().trim())) {
            this.getNameIsExist(entity.getName().trim(), data.getParentId(), data.getSystemId());
        }
        if (Objects.isNull(entity.getVersion())) {
            entity.setVersion(data.getVersion());
        }
        entity.setLevel(this.getLevel(entity.getParentId(), data.getSystemId()));
        if (CharSequenceUtil.isNotBlank(entity.getCode()) && !CharSequenceUtil.equals(data.getCode(), entity.getCode().trim())) {
            this.getCodeIsExist(entity.getCode());
        }
        if (CharSequenceUtil.isNotBlank(entity.getRouteUrl()) && !CharSequenceUtil.equals(data.getRouteUrl(), entity.getRouteUrl().trim())) {
            this.getRouteUrlIsExist(entity.getRouteUrl().trim(), data.getParentId(), data.getSystemId());
        }
        final MenuDO model = BeanUtil.copyProperties(entity, MenuDO.class);
        super.updateById(model);
        this.removeOldPic(entity, data);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editStatus(Long id, EnableStatusEnum status) {
        MenuDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (Boolean.TRUE.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.BUILD_IN_DATA_NOT_OPERATE);
        }
        if (status.equals(data.getStatus())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        MenuDO param = new MenuDO();
        param.setId(id);
        param.setStatus(status);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @CacheEvict(allEntries = true)
    @Override
    public boolean editBuildIn(Long id, Boolean buildInFlag) {
        MenuDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        if (buildInFlag.equals(data.getBuildInFlag())) {
            throw new BizException(BizCodeEnum.ALREADY_OPERATED);
        }
        MenuDO param = new MenuDO();
        param.setId(id);
        param.setBuildInFlag(buildInFlag);
        param.setVersion(data.getVersion());
        super.updateById(param);
        return Boolean.TRUE;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<Tree<Long>> listBySystemId(Long systemId) {
        return this.listBySystemId(systemId, null);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<Tree<Long>> listEnabledBySystemId(Long systemId) {
        return this.listBySystemId(systemId, EnableStatusEnum.ENABLE);
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null && #p1 != null", unless = "#result == null")
    @Override
    public List<MenuTreeSystemVO> listByUserId(Long orgId, Long userId) {
        List<MenuTreeSystemVO> result = new ArrayList<>(16);
        final List<MenuListSystemVO> list = super.baseMapper.selectListByUserId(orgId, userId);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        list.stream().forEach(data -> this.buildMenuListSystem(result, data, this.listTree(data.getMenus(), null)));
        Collections.sort(result, Comparator.comparing(MenuTreeSystemVO::getSeq));
        return result;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0 + '_' + #p1", condition = "#p0 != null", unless = "#result == null")
    @Override
    public List<MenuTreeSystemVO> listByRoleId(Long orgId, Long roleId) {
        List<MenuTreeSystemVO> result = new ArrayList<>(16);
        final List<MenuBaseListSystemVO> allList = super.baseMapper.selectListEnabled();
        if (CollUtil.isEmpty(allList)) {
            return null;
        }
        if (Objects.nonNull(roleId)) {
            final List<MenuBaseListSystemVO> checkedList = super.baseMapper.selectListByRoleId(orgId, roleId);
            if (CollUtil.isNotEmpty(checkedList)) {
                this.buildMenuTree(result, allList, checkedList);
            }
        } else {
            allList.stream().forEach(data -> this.buildMenuBaseListSystem(result, data, this.listBaseTreeChecked(data.getMenus(), null)));
        }
        Collections.sort(result, Comparator.comparing(MenuTreeSystemVO::getSeq));
        return result;
    }

    @Cacheable(key = "#root.methodName + '_' + #p0", condition = "#p0 != null", unless = "#result == null")
    @Override
    public MenuVO getDetail(Long id) {
        MenuDO data = super.getById(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        return BeanUtil.copyProperties(data, MenuVO.class);
    }

    @Override
    public MenuExtendVO getDetailExtend(Long id) {
        MenuVO data = this.getDetail(id);
        if (Objects.isNull(data)) {
            throw new BizException(BizCodeEnum.DATA_NOT_EXIST);
        }
        MenuExtendVO result = BeanUtil.copyProperties(data, MenuExtendVO.class);
        List<String> relativePaths = Lists.newArrayList();
        if (CharSequenceUtil.isNotBlank(data.getIconUrl())) {
            relativePaths.add(data.getIconUrl());
        }
        List<FilePathVO> filePaths = OrgServiceImpl.getFilePaths(this.property.getOss().getTplCode(), relativePaths, this.ossClient);
        if (CollUtil.isNotEmpty(filePaths)) {
            filePaths.forEach(p -> {
                if (CharSequenceUtil.isNotBlank(data.getIconUrl()) && data.getIconUrl().equals(p.getRelativePath())) {
                    result.setIconUrlStr(p.getAbsolutePath());
                }
            });
        }
        return result;
    }

    private List<Tree<Long>> listBySystemId(Long systemId, EnableStatusEnum status) {
        List<MenuBaseTreeVO> list = super.baseMapper.selectListBySystemId(systemId, status);
        if (CollUtil.isEmpty(list)) {
            return null;
        }
        final List<MenuBaseTreeCheckedVO> allList = BeanUtil.copyToList(list, MenuBaseTreeCheckedVO.class);
        return this.listBaseTreeChecked(allList, null);
    }

    private void buildMenuTree(List<MenuTreeSystemVO> list, List<MenuBaseListSystemVO> result,
        List<MenuBaseListSystemVO> checkedList) {
        List<MenuBaseListSystemVO> tempList = new ArrayList<>(10);
        result.stream().forEach(map -> checkedList.stream()
            .filter(m -> Objects.equals(map.getId(), m.getId())).forEach(data -> {
                final List<MenuBaseTreeCheckedVO> menus = this.listWithChecked(map.getMenus(),
                    data.getMenus());
                this.buildMenuBaseListSystem(list, map, this.listBaseTreeChecked(menus, null));
                tempList.add(map);
            }));
        result.removeAll(tempList);
        result.stream().forEach(data -> this.buildMenuBaseListSystem(list, data, this.listBaseTreeChecked(data.getMenus(), null)));
    }

    private void buildMenuBaseListSystem(List<MenuTreeSystemVO> list, MenuBaseListSystemVO entity, List<Tree<Long>> menus) {
        final MenuTreeSystemVO build = MenuTreeSystemVO.builder()
            .id(entity.getId())
            .code(entity.getCode())
            .name(entity.getName())
            .seq(entity.getSeq())
            .menus(menus)
            .build();
        list.add(build);
    }

    private void buildMenuListSystem(List<MenuTreeSystemVO> list, MenuListSystemVO entity, List<Tree<Long>> menus) {
        final MenuTreeSystemVO build = MenuTreeSystemVO.builder()
            .id(entity.getId())
            .code(entity.getCode())
            .name(entity.getName())
            .seq(entity.getSeq())
            .menus(menus)
            .build();
        list.add(build);
    }

    private void getNameIsExist(String name, Long parentId, Long systemId) {
        final LambdaQueryWrapper<MenuDO> queryWrapper = Wrappers.lambdaQuery(MenuDO.class)
            .eq(MenuDO::getSystemId, systemId)
            .eq(MenuDO::getName, name);
        if (Objects.nonNull(parentId)) {
            queryWrapper.eq(MenuDO::getParentId, parentId);
        }
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.NAME_EXIST);
        }
    }

    private void getRouteUrlIsExist(String routeUrl, Long parentId, Long systemId) {
        final LambdaQueryWrapper<MenuDO> queryWrapper = Wrappers.lambdaQuery(MenuDO.class)
            .eq(MenuDO::getSystemId, systemId)
            .eq(MenuDO::getRouteUrl, routeUrl);
        if (Objects.nonNull(parentId)) {
            queryWrapper.eq(MenuDO::getParentId, parentId);
        }
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (Boolean.TRUE.equals(result)) {
            throw new BizException(MgtCodeEnum.ROUTE_URL_EXIST);
        }
    }

    private void getCodeIsExist(String code) {
        final LambdaQueryWrapper<MenuDO> queryWrapper = Wrappers.lambdaQuery(MenuDO.class)
            .eq(MenuDO::getCode, code);
        boolean result = SqlHelper.retBool(super.count(queryWrapper));
        if (result) {
            throw new BizException(MgtCodeEnum.CODE_EXIST);
        }
    }

    private Integer getNextSeq(Long parentId, Long systemId) {
        QueryWrapper<MenuDO> queryWrapper = new QueryWrapper<>();
        if (Objects.nonNull(parentId)) {
            queryWrapper.lambda().eq(MenuDO::getParentId, parentId);
        }
        queryWrapper.lambda().eq(MenuDO::getSystemId, systemId);
        queryWrapper.select("max(seq) as seq");
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(queryWrapper, function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private Integer getLevel(Long parentId, Long systemId) {
        if (Objects.isNull(parentId)) {
            return 1;
        }
        Function<Object, Integer> function = val -> Integer.valueOf(val.toString());
        Integer data = super.getObj(Wrappers.lambdaQuery(MenuDO.class)
            .eq(MenuDO::getId, parentId)
            .eq(MenuDO::getSystemId, systemId)
            .select(MenuDO::getLevel), function);
        return Optional.ofNullable(data).map(x -> x + 1).orElse(1);
    }

    private List<Tree<Long>> listBaseTreeChecked(List<MenuBaseTreeCheckedVO> allList, Long rootId) {
        TreeNodeConfig config = new TreeNodeConfig();
        config.setWeightKey("seq");
        return TreeUtil.build(allList, rootId, config, (object, tree) -> {
            tree.setId(object.getId());
            tree.setParentId(object.getParentId());
            tree.setWeight(object.getSeq());
            tree.setName(object.getName());
            tree.putExtra("level", object.getLevel());
            Boolean checked = object.getChecked();
            if (Objects.nonNull(checked)) {
                tree.putExtra("checked", checked);
            }
        });
    }

    private List<Tree<Long>> listTree(List<MenuTreeVO> allList, Long rootId) {
        TreeNodeConfig config = new TreeNodeConfig();
        config.setWeightKey("seq");
        return TreeUtil.build(allList, rootId, config, (object, tree) -> {
            tree.setId(object.getId());
            tree.setParentId(object.getParentId());
            tree.setWeight(object.getSeq());
            tree.setName(object.getName());
            if (CharSequenceUtil.isNotBlank(object.getIconUrlStr())) {
                tree.putExtra("iconUrlStr", object.getIconUrlStr());
            }
            if (CharSequenceUtil.isNotBlank(object.getIconStyle())) {
                tree.putExtra("iconStyle", object.getIconStyle());
            }
            tree.putExtra("routeUrl", object.getRouteUrl());
            tree.putExtra("level", object.getLevel());
        });
    }

    private List<MenuBaseTreeCheckedVO> listWithChecked(List<MenuBaseTreeCheckedVO> allList, List<MenuBaseTreeCheckedVO> checkedList) {
        return allList.stream().peek(map -> checkedList.stream()
                .filter(m -> Objects.equals(m.getId(), map.getId())).forEach(m -> map.setChecked(m.getChecked())))
            .collect(Collectors.toCollection(ArrayList::new));
    }

    private void removeOldPic(MenuEditDTO entity, MenuDO data) {
        List<String> relativePaths = new ArrayList<>(10);
        if (CharSequenceUtil.isNotBlank(entity.getIconUrl())
            && CharSequenceUtil.isNotBlank(data.getIconUrl())
            && !CharSequenceUtil.equals(data.getIconUrl(), entity.getIconUrl().trim())) {
            relativePaths.add(data.getIconUrl());
        }
        if (CollUtil.isNotEmpty(relativePaths)) {
            OrgServiceImpl.removeFiles(this.ossClient, this.property.getOss().getTplCode(), relativePaths);
        }
    }
}
